package com.sangeng.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sangeng.constants.SystemConstants;
import com.sangeng.domain.entity.LoginUser;
import com.sangeng.domain.entity.User;
import com.sangeng.mapper.MenuMapper;
import com.sangeng.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    //查询权限 封装能够用的菜单进User
    private final MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        // 在authenticationManager对authenticationToken封装好后，最终会返回到UserDetails，它会调用这个方法
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(queryWrapper);
        //判断是否查到用户  如果没查到抛出异常
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户不存在");
        }
        // 返回用户信息

        /* 为什么返回用户信息这里要存入权限信息？
        * 假设没有封装权限信息的话，友链管理员知道超级管理员一些权限的接口地址，就仍能调用不属于自己的权限接口了。
        * 查询权限信息封装到user当中，存入SecurityContextHolder
          如果是后台用户才需要查询权限信息封装
        * */
        if(user.getType().equals(SystemConstants.ADMIN)) {
            List<String> menuList = menuMapper.selectPermsByUserId(user.getId());
            return new LoginUser(user, menuList);
        }

        //不是后台用户 传permissions为null 因为前面LoginUser的构造是 全参 or 空参
        return new LoginUser(user,null);
    }
}